import * as TYPES from "../action-types";
import { getSongCategory, getSongCategoryList } from "services/songs";

let actions = {
  // redux-promise
  getSongCat: async () => {
    return {
      type: TYPES.SONG_CAT,
      payload: await getSongCategory().then((res) => {
        const { categories, sub } = res;
        let obj = {};
        for (const key in categories) {
          if (Object.hasOwnProperty.call(categories, key)) {
            const element = categories[key];
            obj[element] = sub.filter((item) => item.category === +key);
          }
        }
        return { ...obj };
      }),
    };
  },
  getSongCatList: () => {
    return async (dispatch, getState) => {
      const songCatParams = getState().getIn(["songlist", "songCatParams"]);
      const res = await getSongCategoryList(songCatParams);
      dispatch({
        type: TYPES.SONG_LIST,
        payload: res,
      });
    };
  },
  songChangeBy: (payload) => {
    return (dispatch, getState) => {
      const songCatParams = getState().getIn(["songlist", "songCatParams"]);
      if (
        songCatParams.cat === payload.cat &&
        songCatParams.offset === payload.offset
      )
        return;
      const data = { ...songCatParams, ...payload };
      dispatch({
        type: TYPES.CHANGE_CURRENT_CATEGORY,
        payload: data,
      });
      dispatch(actions.getSongCatList());
    };
  },
};

export default actions;
